package com.huige.wiki.interceptor;

import com.huige.wiki.WikiApplication;
import com.huige.wiki.util.RequestContext;
import com.huige.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LogInterceptor implements HandlerInterceptor {

    @Resource
    private SnowFlake snowFlake;

    private static final Logger LOG = LoggerFactory.getLogger(LogInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 增加日志流水号码
        MDC.put("LOG_ID", String.valueOf(snowFlake.nextId()));
        // 打印请求信息
        LOG.info("------------------------拦截器开始--------------------");
        LOG.info("请求地址：{}{}",request.getRequestURL().toString(),request.getMethod());
        LOG.info("远程地址：{}{}",request.getRemoteAddr());
        
        // 把客户端ip封装设置到上下文中，方便后续业务使用
        RequestContext.setRemoteAddr(getRemote(request));

        long startTime = System.currentTimeMillis();
        request.setAttribute("requestStartTime",startTime);
        return true;
    }

    /**
     *  使用nginx做反向代理，需要用该方法才能取到真实的远程IP
     * @param request
     * @return
     */
    private String getRemote(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip==null || ip.length()==0 || "unknow".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (Long)request.getAttribute("requestStartTime");
        LOG.info("---------------------------拦截结束 耗时：{}ms",System.currentTimeMillis()-startTime);

    }
}
